<template>
	<view class="record-entry-page">
		<!-- 顶部标题栏 -->
		<view class="header">
			<text class="page-title">护理记录录入</text>
			<text class="elderly-info">{{ elderlyInfo.name || '选择老人' }}</text>
		</view>

		<!-- 记录表单 -->
		<view class="form-container">
			<!-- 老人选择 -->
			<view class="form-section">
				<text class="section-title">基本信息</text>
				<view class="form-item">
					<text class="form-label">选择老人 <text class="required">*</text></text>
					<picker @change="onElderlyChange" :value="elderlyIndex" :range="elderlyOptions" range-key="name">
						<view class="picker-input">
							<text class="picker-text">{{ elderlyInfo.name || '请选择老人' }}</text>
							<text class="picker-arrow">></text>
						</view>
					</picker>
				</view>
				<view class="form-item">
					<text class="form-label">记录时间 <text class="required">*</text></text>
					<picker mode="datetime" @change="onDateTimeChange" :value="formData.record_time">
						<view class="picker-input">
							<text class="picker-text">{{ formData.record_time || '请选择时间' }}</text>
							<text class="picker-arrow">></text>
						</view>
					</picker>
				</view>
			</view>

			<!-- 健康指标 -->
			<view class="form-section">
				<text class="section-title">健康指标</text>
				<view class="form-item">
					<text class="form-label">体温 (℃)</text>
					<input class="form-input" v-model="formData.health_temperature" placeholder="请输入体温" type="digit" />
				</view>
				<view class="form-item">
					<text class="form-label">血压</text>
					<input class="form-input" v-model="formData.health_pressure" placeholder="请输入血压值" />
				</view>
				<view class="form-item">
					<text class="form-label">心率 (次/分)</text>
					<input class="form-input" v-model="formData.health_rate" placeholder="请输入心率" type="number" />
				</view>
			</view>

			<!-- 饮食记录 -->
			<view class="form-section">
				<text class="section-title">饮食记录</text>
				<view class="form-item">
					<text class="form-label">早餐</text>
					<textarea class="form-textarea" v-model="formData.food_morning" placeholder="请输入早餐内容，如：牛奶、鸡蛋、稀饭、春卷"></textarea>
				</view>
				<view class="form-item">
					<text class="form-label">午餐</text>
					<textarea class="form-textarea" v-model="formData.food_noon" placeholder="请输入午餐内容，如：番茄鸡蛋、红烧肉、紫菜汤"></textarea>
				</view>
				<view class="form-item">
					<text class="form-label">晚餐</text>
					<textarea class="form-textarea" v-model="formData.food_evening" placeholder="请输入晚餐内容，如：牛奶、鸡蛋、稀饭、春卷"></textarea>
				</view>
			</view>

			<!-- 护理活动 -->
			<view class="form-section">
				<text class="section-title">护理活动</text>
				<view class="form-item">
					<text class="form-label">活动标题 <text class="required">*</text></text>
					<input class="form-input" v-model="formData.title" placeholder="请输入活动标题，如：定时喂药-阿莫西林" />
				</view>
				<view class="form-item">
					<text class="form-label">详细描述</text>
					<textarea class="form-textarea" v-model="formData.remark" placeholder="请输入详细描述信息"></textarea>
				</view>
			</view>

			<!-- 图片上传 -->
			<view class="form-section">
				<text class="section-title">相关图片</text>
				<view class="upload-section">
					<view class="image-list">
						<view class="image-item" v-for="(image, index) in imageList" :key="index">
							<image class="uploaded-image" :src="image" mode="aspectFill"></image>
							<view class="remove-btn" @tap="removeImage(index)">
								<text class="remove-icon">×</text>
							</view>
						</view>
						<view class="add-image-btn" @tap="chooseImage" v-if="imageList.length < 9">
							<text class="add-icon">+</text>
							<text class="add-text">添加图片</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="submit-section">
			<button class="submit-btn" @tap="submitRecord" :disabled="submitting">
				<text class="submit-text">{{ submitting ? '提交中...' : '提交记录' }}</text>
			</button>
		</view>
	</view>
</template>

<script>
import { apiAddElderlyRecord, apiGetElderlyMembers } from '@/request/api.js'

export default {
	data() {
		return {
			formData: {
				member_id: '',
				health_temperature: '',
				health_pressure: '',
				health_rate: '',
				food_morning: '',
				food_noon: '',
				food_evening: '',
				title: '',
				remark: '',
				record_time: ''
			},
			imageList: [],
			elderlyList: [],
			elderlyIndex: 0,
			submitting: false
		}
	},
	computed: {
		elderlyOptions() {
			return this.elderlyList.filter(elderly => elderly.name && elderly.id);
		},
		elderlyInfo() {
			return this.elderlyOptions[this.elderlyIndex] || {};
		}
	},
	onLoad(options) {
		// 初始化时间为当前时间
		this.formData.record_time = this.getCurrentDateTime();
		
		// 如果传入了老人ID，设置选中状态
		if (options.memberId) {
			this.formData.member_id = options.memberId;
		}
		
		// 加载老人列表
		this.loadElderlyList();
	},
	methods: {
		// 加载老人列表
		async loadElderlyList() {
			try {
				// 获取用户信息
				const userInfo = uni.getStorageSync('userInfo');
				const uid = userInfo && userInfo.uid ? userInfo.uid : '33897';
				
				const response = await apiGetElderlyMembers({
					uid: uid,
					page: 1,
					limit: 100
				});
				
				if (response.code === 0) {
					this.elderlyList = response.data.filter(member => member.name && member.id);
					
					// 如果有预选的老人ID，设置选中状态
					if (this.formData.member_id) {
						const index = this.elderlyList.findIndex(elderly => elderly.id == this.formData.member_id);
						if (index >= 0) {
							this.elderlyIndex = index;
						}
					}
				}
			} catch (error) {
				console.error('加载老人列表失败:', error);
				uni.showToast({
					title: '加载老人列表失败',
					icon: 'none'
				});
			}
		},
		
		// 老人选择改变
		onElderlyChange(e) {
			this.elderlyIndex = e.detail.value;
			this.formData.member_id = this.elderlyInfo.id;
		},
		
		// 时间选择改变
		onDateTimeChange(e) {
			this.formData.record_time = e.detail.value;
		},
		
		// 获取当前日期时间
		getCurrentDateTime() {
			const now = new Date();
			const year = now.getFullYear();
			const month = (now.getMonth() + 1).toString().padStart(2, '0');
			const day = now.getDate().toString().padStart(2, '0');
			const hour = now.getHours().toString().padStart(2, '0');
			const minute = now.getMinutes().toString().padStart(2, '0');
			return `${year}-${month}-${day} ${hour}:${minute}:00`;
		},
		
		// 选择图片
		chooseImage() {
			uni.chooseImage({
				count: 9 - this.imageList.length,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					this.imageList = [...this.imageList, ...res.tempFilePaths];
				},
				fail: (error) => {
					console.error('选择图片失败:', error);
					uni.showToast({
						title: '选择图片失败',
						icon: 'none'
					});
				}
			});
		},
		
		// 移除图片
		removeImage(index) {
			this.imageList.splice(index, 1);
		},
		
		// 验证表单
		validateForm() {
			if (!this.formData.member_id) {
				uni.showToast({
					title: '请选择老人',
					icon: 'none'
				});
				return false;
			}
			
			if (!this.formData.title.trim()) {
				uni.showToast({
					title: '请输入活动标题',
					icon: 'none'
				});
				return false;
			}
			
			if (!this.formData.record_time) {
				uni.showToast({
					title: '请选择记录时间',
					icon: 'none'
				});
				return false;
			}
			
			return true;
		},
		
		// 提交记录
		async submitRecord() {
			if (!this.validateForm()) return;
			
			this.submitting = true;
			
			try {
				// 准备提交数据
				const submitData = {
					member_id: this.formData.member_id,
					health_temperature: this.formData.health_temperature || '',
					health_pressure: this.formData.health_pressure || '',
					health_rate: this.formData.health_rate || '',
					food_morning: this.formData.food_morning || '',
					food_noon: this.formData.food_noon || '',
					food_evening: this.formData.food_evening || '',
					title: this.formData.title,
					remark: this.formData.remark || '',
					record_time: this.formData.record_time
				};
				
				// 处理图片列表
				if (this.imageList.length > 0) {
					// 将图片路径用|分隔
					submitData['pics[]'] = this.imageList.join('|');
				}
				
				const response = await apiAddElderlyRecord(submitData);
				
				if (response.code === 0) {
					uni.showToast({
						title: '记录提交成功',
						icon: 'success'
					});
					
					// 延迟返回上一页
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				}
			} catch (error) {
				console.error('提交记录失败:', error);
				uni.showToast({
					title: '提交失败，请重试',
					icon: 'none'
				});
			} finally {
				this.submitting = false;
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.record-entry-page {
	min-height: 100vh;
	background: #F8F8F8;
	padding-bottom: 120rpx;
}

.header {
	background: linear-gradient(135deg, #FF7D00 0%, #FF4856 100%);
	padding: 60rpx 30rpx 30rpx;
	color: #FFFFFF;
}

.page-title {
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 10rpx;
	display: block;
}

.elderly-info {
	font-size: 26rpx;
	opacity: 0.9;
}

.form-container {
	padding: 20rpx;
}

.form-section {
	background: #FFFFFF;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 30rpx;
	display: block;
	border-left: 6rpx solid #FF7D00;
	padding-left: 20rpx;
}

.form-item {
	margin-bottom: 30rpx;
}

.form-item:last-child {
	margin-bottom: 0;
}

.form-label {
	font-size: 28rpx;
	color: #666666;
	margin-bottom: 16rpx;
	display: block;
}

.required {
	color: #FF4444;
}

.form-input, .form-textarea {
	width: 100%;
	border: 2rpx solid #E0E0E0;
	border-radius: 12rpx;
	padding: 20rpx;
	font-size: 28rpx;
	color: #333333;
	background: #FFFFFF;
	box-sizing: border-box;
}

.form-input {
	height: 80rpx;
}

.form-textarea {
	min-height: 120rpx;
	resize: none;
}

.form-input:focus, .form-textarea:focus {
	border-color: #FF7D00;
	outline: none;
}

.picker-input {
	display: flex;
	justify-content: space-between;
	align-items: center;
	border: 2rpx solid #E0E0E0;
	border-radius: 12rpx;
	padding: 20rpx;
	background: #FFFFFF;
	min-height: 40rpx;
}

.picker-text {
	font-size: 28rpx;
	color: #333333;
	flex: 1;
}

.picker-arrow {
	font-size: 24rpx;
	color: #999999;
	margin-left: 20rpx;
}

.upload-section {
	margin-top: 20rpx;
}

.image-list {
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
}

.image-item {
	position: relative;
	width: 200rpx;
	height: 200rpx;
	border-radius: 12rpx;
	overflow: hidden;
}

.uploaded-image {
	width: 100%;
	height: 100%;
}

.remove-btn {
	position: absolute;
	top: 10rpx;
	right: 10rpx;
	width: 44rpx;
	height: 44rpx;
	background: rgba(0, 0, 0, 0.6);
	border-radius: 22rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.remove-icon {
	color: #FFFFFF;
	font-size: 28rpx;
	font-weight: bold;
}

.add-image-btn {
	width: 200rpx;
	height: 200rpx;
	border: 2rpx dashed #CCCCCC;
	border-radius: 12rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background: #F8F8F8;
}

.add-icon {
	font-size: 48rpx;
	color: #999999;
	margin-bottom: 10rpx;
}

.add-text {
	font-size: 24rpx;
	color: #999999;
}

.submit-section {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: #FFFFFF;
	padding: 30rpx;
	box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.submit-btn {
	width: 100%;
	height: 88rpx;
	background: linear-gradient(135deg, #FF7D00 0%, #FF4856 100%);
	border-radius: 44rpx;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
}

.submit-btn[disabled] {
	background: #CCCCCC;
	opacity: 0.6;
}

.submit-text {
	color: #FFFFFF;
	font-size: 32rpx;
	font-weight: bold;
}
</style>
